//
//  RearViewController.m
//  KurtulusLaw
//
//  Created by phuc phuc on 12/1/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "RearViewController.h"
#import "KurtulusLawController.h"
#import "FrontViewController.h"
#import "CasesViewController.h"
#import "InvoicesViewController.h"
#import "DocumentView.h"
#import "MeetingRequestTableViewController.h"
#import "SettingViewController.h"
#import "Constant.h"
#import "UserService.h"
#import "MBProgressHUD.h"
#import "UserDTO.h"
@interface RearViewController() <UIAlertViewDelegate>
{
	MBProgressHUD *_progressHUD;
	UserDTO *userDTO;
	UIButton *btnEmail;
	UILabel *navName;
}
@property (nonatomic,strong) UserDTO *userDTO;
@end

@implementation RearViewController

@synthesize rearTableView = _rearTableView;
@synthesize barButtonLeft = _barButtonLeft;
@synthesize userDTO;

static UserDTO *_userDTO = nil;

#pragma mark DocumentInteractionViewController delegates

- (UIViewController *) documentInteractionControllerViewControllerForPreview: (UIDocumentInteractionController *) controller {
	return self;
}

#pragma mark - get profile data
-(void) getProfile : (NSString*) _session
{
	[UserService getProfileWithSessionID:_session :^(id dictionary, NSError *error) {
		if (error) {
			UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Message", nil) message: [error localizedDescription] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
			[alert show];
			[_progressHUD hide:YES];
		}
		else
		{
			@try {
				NSLog(@"%@",dictionary);
				if ([[dictionary objectForKey:@"status"] isEqualToString:@"OK"]) {
					self.userDTO = [[UserDTO alloc] initProfile: dictionary];
					_userDTO = self.userDTO;
					NSString *strEmail = [self.userDTO email];
					[btnEmail setTitle: strEmail  forState:UIControlStateNormal];
					if ([[self.userDTO company_name]length] != 0) {
						navName.text = [self.userDTO company_name];
					}
					else
					{
						NSString *strName = [NSString stringWithFormat:@"%@",[self.userDTO lastname]];
						navName.text = strName;
					}
					NSLog(@"%@",self.userDTO);
					[_progressHUD hide:YES];
				}
				else
				{
					UIAlertView *alert = [[UIAlertView alloc] initWithTitle: NSLocalizedString(@"Message", nil) message: NSLocalizedString(@"Can't get data from server", nil) delegate:nil cancelButtonTitle: NSLocalizedString(@"OK", nil) otherButtonTitles:nil, nil];
					[alert show];
					[_progressHUD hide:YES];
				}
			}
			@catch (NSException *exception) {
				[_progressHUD hide:YES];
			}
			@finally {
				//
			}
		}
		
	}];
}

#pragma mark - ------------- 
-(void)setting: (id) sender
{
    
}
- (void)createControlOnNavigation
{
    UINavigationBar *navBar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
    //navBar.barStyle = UIBarStyleBlack; 
    //navBar.translucent = YES;
   
    btnEmail = [UIButton buttonWithType:UIButtonTypeCustom];
    btnEmail.frame = CGRectMake(50,25,220,15);
    btnEmail.titleLabel.textColor = [UIColor whiteColor];
    btnEmail.titleLabel.font = [UIFont boldSystemFontOfSize:12.0f];
    [btnEmail.titleLabel setTextAlignment:UITextAlignmentLeft];
    btnEmail.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    
    [btnEmail addTarget:self  
                 action:@selector(pushToMail:)forControlEvents:UIControlEventTouchUpInside];
    
    navName = [[UILabel alloc] initWithFrame:CGRectMake(50,5,220,15)];
    
    navName.font = [UIFont boldSystemFontOfSize:12.0f];
    navName.textColor = [UIColor whiteColor];
    navName.backgroundColor = [UIColor clearColor];
    
    [navBar addSubview:btnEmail];
    [navBar addSubview:navName];
    
    [self.view addSubview:navBar];
    
    UIButton *btnSetting = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 41, 46)];
    btnSetting.tintColor = [UIColor blackColor];
    [btnSetting setImage:[UIImage imageNamed:kImageSetting34x46] forState:UIControlStateNormal];
    [btnSetting setContentHorizontalAlignment:UIControlContentHorizontalAlignmentRight];
    [btnSetting addTarget:self action:@selector(selectSetting:) forControlEvents:UIControlEventTouchUpInside];
    [navBar addSubview:btnSetting];

     [navBar setBackgroundImage:[UIImage imageNamed:@"nav-bg-black.png"] forBarMetrics:UIBarMetricsDefault];
}

-(void) pushToMail : (id) sender
{
    MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
    picker.mailComposeDelegate = self;
    [picker setSubject:@"Kurtulus & Partners"];
    // Set up recipients
	
    NSArray *toRecipients = [NSArray arrayWithObject: kMailHasanKurtulus];
    NSString *emailBody = @"";
	
    [picker setToRecipients:toRecipients];
    [picker setMessageBody:emailBody isHTML:NO];
    [self presentModalViewController:picker animated:YES];
}
-(void) openProfileCompany : (id)sender
{
	@try {
		NSString *documentPath = [[NSBundle mainBundle] pathForResource:@"brochure" ofType:@"pdf"];
		NSURL *documentURL = [NSURL fileURLWithPath:documentPath isDirectory:NO];
		documentationInteraction = [UIDocumentInteractionController interactionControllerWithURL:documentURL];
		documentationInteraction.delegate = self;
		[documentationInteraction presentPreviewAnimated:YES];
	}
	@catch (NSException *exception) {
		NSLog(@"%@",exception);
	}
	@finally {
		//
	}
	
}
-(void) pushToMail1 : (id) sender
{
    MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
    picker.mailComposeDelegate = self;
    [picker setSubject:@"Kurtulus & Partners"];
    // Set up recipients
	
    NSArray *toRecipients = [NSArray arrayWithObject: kMailSupportKurtulus];
    NSString *emailBody =  NSLocalizedString(@"How may we help you? Please explain in details\nPlease give us your contact details;\nName & Surname :\nCompany Name  :\nTelephone      :\nSkype          :", nil);
	
    [picker setToRecipients:toRecipients];
    [picker setMessageBody:emailBody isHTML:NO];
    [self presentModalViewController:picker animated:YES];
}
#pragma mark - alert delegate
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (buttonIndex) {
        case 0:
            NSLog(@"no call");
            //no
            break;
        case 1:
            NSLog(@"yes call");
            [CCommon callToKurtulus];
            //yes
            break;
        default:
            break;
    }
}



- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error
{
    // Notifies users about errors associated with the interface
    switch (result)
    {
        case MFMailComposeResultCancelled:
            NSLog(@"Result: canceled");
            break;
        case MFMailComposeResultSaved:
            NSLog(@"Result: saved");
            break;
        case MFMailComposeResultSent:
            NSLog( @"Result: sent");
            break;
        case MFMailComposeResultFailed:
            NSLog( @"Result: failed");
            break;
        default:
            NSLog( @"Result: not sent");
            break;
    }
    [self dismissModalViewControllerAnimated:YES];
}
- (void)btnCallKurtulus:(id)sender
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle: NSLocalizedString(@"Message", nil) message: NSLocalizedString(@"Do you want to call Kurtulus&Partners", nil) delegate:self cancelButtonTitle: NSLocalizedString(@"Cancel", nil) otherButtonTitles:NSLocalizedString(@"OK", nil), nil];
    [alert show];
}

-(void)btnCallSkype : (id) sender
{
	NSString *stringURL = [NSString stringWithFormat:@"skype:%@?chat",kSkypeKurtulus];
	NSURL *url = [NSURL URLWithString:stringURL];
	[[UIApplication sharedApplication] openURL:url];
}


-(void)viewDidLoad
{
    [super viewDidLoad];
	_progressHUD.dimBackground = YES;
	_progressHUD.labelText = NSLocalizedString(@"Loading", nil);
	[self.view addSubview:_progressHUD];
	
    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bgback.png"]];
    self.rearTableView.backgroundColor = [UIColor clearColor];
    [self createControlOnNavigation];
     [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"nav-bg-black"] forBarMetrics:UIBarMetricsDefault] ;
	
	NSString *sessionID = [CCommon shareSessionID];
	NSLog(@"session ID : %@",sessionID);
	[self getProfile: sessionID];
	
}

-(void)selectSetting:(id)sender
{
    NSLog(@"click");
    SettingViewController *setting = [[SettingViewController alloc] init];
    //self.navigationController
    UINavigationController *navigation  = [[UINavigationController alloc] initWithRootViewController:setting];
    
    [navigation setModalTransitionStyle:UIModalTransitionStyleFlipHorizontal];
    [self presentModalViewController:navigation animated:YES];
}

#pragma marl - UITableView Data Source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
	return section == 0 ? 5 : 4;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    if (section == 1) {
        NSString *sectionTitle = @" KURTULUS";
        
        // Create label with section title
        UILabel *label = [[UILabel alloc] init] ;
        label.frame = CGRectMake(0, 0, 284, 23);
        label.textColor = [UIColor blackColor];
        label.font = [UIFont boldSystemFontOfSize:16.0f];
        label.text = sectionTitle;
        label.backgroundColor = [UIColor clearColor];
        [label setFont:[UIFont fontWithName:@"Arial-BoldMT" size:16.0f]];
        [label sizeToFit];
        
        UILabel *label2 =  [[UILabel alloc] init] ;
        label2.textColor = [UIColor blackColor];
        label2.font = [UIFont boldSystemFontOfSize:15.0f];
        label2.backgroundColor = [UIColor clearColor];
      

        [label2 setText:@"&PARTNERS"];
        [label2 setFont:[UIFont systemFontOfSize:15.0f]];
        [label2 setFont:[UIFont fontWithName:@"AppleGothic" size:15.0f]];
        [label2 sizeToFit];
        [label2 setFrame:CGRectMake(label.frame.origin.x + label.frame.size.width, 0, label2.frame.size.width , label2.frame.size.height)];
        [label2 setCenter:CGPointMake(label2.center.x, label.center.y + 0.5)];
        // Create header view and add label as a subview
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 100)];
        [view addSubview:label];
        [view addSubview:label2];
        return view;
    }
    else
    {
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 20)];
        return view;
    }
    
}
- (UIView*) tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 30)];
    return view;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return section == 0 ? 20 : 25;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return section == 0 ? 25 : 5;
}
-(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return indexPath.section == 0 ? 38.0f : 36.0f;;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	static NSString *cellIdentifier = @"Cell";
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    
    switch (indexPath.section) {
        case 0:
        {
            if (indexPath.row == 0)
            {
				cell.textLabel.text = NSLocalizedString(@"My Profile", nil);
                
            }
            else if (indexPath.row == 1)
            {
                cell.textLabel.text = NSLocalizedString(@"Cases", nil);
            }
            else if (indexPath.row == 2)
            {
                cell.textLabel.text = NSLocalizedString(@"Invoices", nil);
            }
            else if (indexPath.row == 3)
            {
                cell.textLabel.text = NSLocalizedString(@"Documents", nil);
            }
            else if (indexPath.row == 4)
            {
                cell.textLabel.text = NSLocalizedString(@"Meeting Request", nil);
            }
            cell.textLabel.textColor = [UIColor grayColor];
            cell.textLabel.font = [UIFont systemFontOfSize:18.0f];
            return cell;
        }
        case 1:
        {
            NSString *imageString = @"";
            if (indexPath.row == 0)
            {
                imageString = kImage_RearView_p;
                cell.textLabel.text = NSLocalizedString(@"Company Profile", nil);
                
                UIImageView *image = [[UIImageView alloc] initWithImage:[UIImage imageNamed:kIconPDF]];
                [image setFrame:CGRectMake(145, 6, 24, 24)];
                [cell.contentView addSubview:image];
            }
            else if (indexPath.row == 1)
            {
                imageString = kImage_RearView_e;
                cell.textLabel.text = kMailSupportKurtulus;
            }
            else if (indexPath.row == 2)
            {
                imageString = kImage_RearView_t;
                cell.textLabel.text = kPhoneNumber;
            }
            else if (indexPath.row == 3)
            {
                cell.textLabel.text = @"kurtuluspartners";
                imageString = kImageMeetingTypeIcon24x24;
            }
            
            cell.imageView.image = [UIImage imageNamed:imageString];
            cell.textLabel.font = [UIFont systemFontOfSize:10.0f];
            [cell.textLabel setTextColor:[UIColor grayColor]];
            return cell;
        }
            
        default:
            break;
    }
		
	return cell;
}
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    
    if (indexPath.section == 0) {
        
        cell.backgroundView = [ [UIImageView alloc] initWithImage:[ [UIImage imageNamed:@"rear-below-cell-202x38.png"] stretchableImageWithLeftCapWidth:0.0 topCapHeight:5.0] ]; 
        cell.selectedBackgroundView = [[UIImageView alloc] initWithImage:[ [UIImage imageNamed:@"rear-below-selection-cell-202x38.png"] stretchableImageWithLeftCapWidth:0.0 topCapHeight:5.0]];
    }
    else
    {
        cell.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"cell-bg-2x35"]];
        cell.selectionStyle = UITableViewCellSelectionStyleGray;
        
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
	KurtulusLawController *revealController = [self.parentViewController isKindOfClass:[KurtulusLawController class]] ? (KurtulusLawController *)self.parentViewController : nil;
    if (indexPath.section == 0) 
	{
        if (indexPath.row == 0)
        {
            if ([revealController.frontViewController isKindOfClass:[UINavigationController class]] && ![((UINavigationController *)revealController.frontViewController).topViewController isKindOfClass:[FrontViewController class]])
            {
                FrontViewController *frontViewController = [[FrontViewController alloc] init];
                UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:frontViewController];
                [revealController setFrontViewController:navigationController animated:NO];
                
            }
            else
            {
                [revealController revealToggle:self];
            }
        }
        else if (indexPath.row == 1)
        {
            if ([revealController.frontViewController isKindOfClass:[UINavigationController class]] && ![((UINavigationController *)revealController.frontViewController).topViewController isKindOfClass:[CasesViewController class]])
            {
                CasesViewController *casesController = [[CasesViewController alloc] init];
                UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:casesController];
                [revealController setFrontViewController:navigationController animated:NO];
            }
            
            else
            {
                [revealController revealToggle:self];
            }
        }
        else if (indexPath.row == 2)
        {
            if ([revealController.frontViewController isKindOfClass:[UINavigationController class]] && ![((UINavigationController *)revealController.frontViewController).topViewController isKindOfClass:[InvoicesViewController class]])
            {
                InvoicesViewController *invoiceController = [[InvoicesViewController alloc] init];
                UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:invoiceController];
                [revealController setFrontViewController:navigationController animated:NO];
            }
            
            else
            {
                [revealController revealToggle:self];
            }
        }
        else if (indexPath.row == 3)
        {
            if ([revealController.frontViewController isKindOfClass:[UINavigationController class]] && ![((UINavigationController *)revealController.frontViewController).topViewController isKindOfClass:[DocumentView class]])
            {
                DocumentView *documentController = [[DocumentView alloc] init];
                UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:documentController];
                [revealController setFrontViewController:navigationController animated:NO];
            }
            
            else
            {
                [revealController revealToggle:self];
            }
        }
        else if (indexPath.row == 4) 
        {
            if ([revealController.frontViewController isKindOfClass:[UINavigationController class]] && ![((UINavigationController *)revealController.frontViewController).topViewController isKindOfClass:[MeetingRequestTableViewController class]])
            {
                MeetingRequestTableViewController *mettingController = [[MeetingRequestTableViewController alloc] init];
                UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:mettingController];
                [revealController setFrontViewController:navigationController animated:NO];
            }
            
            else
            {
                [revealController revealToggle:self];
            }

        }

    }
	else
	{
		switch (indexPath.row) {
			case 0:
				//company profile
				[self openProfileCompany:self];
				break;
			case 1:
				[self pushToMail1:self];
				break;
			case 2:
				[self btnCallKurtulus:self];
				break;
			case 3:
				[self btnCallSkype:self];
				break;
			default:
				break;
		}
	}
	
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
{
	return (toInterfaceOrientation == UIInterfaceOrientationPortrait);
}
- (void)viewDidUnload {
    [self setBarButtonLeft:nil];
    [super viewDidUnload];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}

+(UserDTO*) getUserDTO
{
	return _userDTO;
}

@end

